package com.atguigu.exam.service.impl;

import com.atguigu.exam.entity.Banner;
import com.atguigu.exam.mapper.BannerMapper;
import com.atguigu.exam.service.BannerService;

import com.atguigu.exam.service.FileUploadService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 轮播图服务实现类
 */
@Service
@Slf4j
public class BannerServiceImpl extends ServiceImpl<BannerMapper, Banner> implements BannerService {
    @Autowired
    private FileUploadService fileUploadService;

    /**
     * 上传轮播图图片服务
     *
     * @param file
     * @return
     */
    @Override
    public String uploadBannerImage(MultipartFile file) throws Exception {
        //图片进行非空校验
        if (file.isEmpty()) {
            throw new RuntimeException("轮播图图片不可以为空");
        }
        //文件格式校验
        if (!file.getContentType().startsWith("image")) {
            throw new RuntimeException("上传的文件格式为非图片!");
        }
        //调用文件上传通用业务
        String url = fileUploadService.uploadFile(file, "banners");
        //返回url
        return url;
    }

    /**
     * 添加轮播图业务员
     *
     * @param banner
     */
    @Override
    public void addBanner(Banner banner) {
        //判断启动状态
        if (banner.getIsActive() == null) {
            banner.setIsActive(true);
        }
        //判断优先级
        if (banner.getSortOrder() == null) {
            banner.setSortOrder(1);
        }

        //保存轮播图
        boolean save = save(banner);
        if (!save) {
            throw new RuntimeException("保存轮播图失败");
        }
        log.info("保存轮播图成功");
    }

    /**
     * 更新轮播图业务
     *
     * @param banner
     */
    @Override
    public void updateBanner(Banner banner) {
        boolean updated = updateById(banner);
        if (!updated){
            throw new RuntimeException("更新轮播图失败");
        }
        log.info("更新轮播图成功");
    }
}